package com.zenithmind.task.controller;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.task.pojo.entity.TaskDependency;
import com.zenithmind.task.pojo.query.TaskDependencyQuery;
import com.zenithmind.task.pojo.vo.TaskDependencyVO;
import com.zenithmind.task.service.TaskDependencyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 任务依赖管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/task-dependency")
@RequiredArgsConstructor
@Tag(name = "任务依赖管理", description = "任务依赖关系的创建、查询、删除等功能")
public class TaskDependencyController {

    private final TaskDependencyService taskDependencyService;

    // ==================== 基础CRUD操作 ====================

    @GetMapping("/page")
    @Operation(summary = "分页查询任务依赖列表", description = "支持多条件筛选的任务依赖分页查询")
    public Result<PageResult<TaskDependencyVO>> getTaskDependencyPage(TaskDependencyQuery query) {
        String userId = UserContext.requireUserId();
        PageResult<TaskDependencyVO> result = taskDependencyService.getTaskDependencyPage(query, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询任务依赖详情", description = "根据ID查询任务依赖的详细信息")
    public Result<TaskDependencyVO> getTaskDependencyById(@Parameter(description = "依赖ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        TaskDependencyVO taskDependency = taskDependencyService.getTaskDependencyById(id, userId);
        return Result.success(taskDependency);
    }

    @PostMapping
    @Operation(summary = "创建任务依赖", description = "创建新的任务依赖关系")
    public Result<Boolean> createTaskDependency(@Valid @RequestBody TaskDependency taskDependency) {
        String userId = UserContext.requireUserId();
        Boolean result = taskDependencyService.createTaskDependency(taskDependency, userId);
        return Result.success(result);
    }

    @PutMapping
    @Operation(summary = "更新任务依赖", description = "更新任务依赖信息")
    public Result<Boolean> updateTaskDependency(@Valid @RequestBody TaskDependency taskDependency) {
        String userId = UserContext.requireUserId();
        Boolean result = taskDependencyService.updateTaskDependency(taskDependency, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除任务依赖", description = "删除指定的任务依赖关系")
    public Result<Boolean> deleteTaskDependency(@Parameter(description = "依赖ID") @PathVariable String id) {
        String userId = UserContext.requireUserId();
        Boolean result = taskDependencyService.deleteTaskDependency(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除任务依赖", description = "批量删除多个任务依赖关系")
    public Result<Boolean> batchDeleteTaskDependencies(@RequestBody List<String> ids) {
        String userId = UserContext.requireUserId();
        Boolean result = taskDependencyService.batchDeleteTaskDependencies(ids, userId);
        return Result.success(result);
    }

    // ==================== 依赖关系操作 ====================

    @PostMapping("/add")
    @Operation(summary = "添加任务依赖", description = "在两个任务之间添加依赖关系")
    public Result<Boolean> addTaskDependency(
            @Parameter(description = "前置任务ID") @RequestParam String predecessorId,
            @Parameter(description = "后续任务ID") @RequestParam String successorId,
            @Parameter(description = "依赖类型") @RequestParam(defaultValue = "1") Integer dependencyType,
            @Parameter(description = "延迟天数") @RequestParam(defaultValue = "0") Integer lagDays,
            @Parameter(description = "备注") @RequestParam(required = false) String remark) {
        String userId = UserContext.requireUserId();
        
        TaskDependency taskDependency = new TaskDependency();
        taskDependency.setPredecessorId(predecessorId);
        taskDependency.setSuccessorId(successorId);
        taskDependency.setDependencyType(dependencyType);
        taskDependency.setLagDays(lagDays);
        taskDependency.setRemark(remark);
        
        Boolean result = taskDependencyService.createTaskDependency(taskDependency, userId);
        return Result.success(result);
    }

    @DeleteMapping("/remove")
    @Operation(summary = "移除任务依赖", description = "移除两个任务之间的依赖关系")
    public Result<Boolean> removeTaskDependency(
            @Parameter(description = "前置任务ID") @RequestParam String predecessorId,
            @Parameter(description = "后续任务ID") @RequestParam String successorId) {
        String userId = UserContext.requireUserId();
        // TODO: 实现根据前置和后续任务ID查找并删除依赖关系
        return Result.success(true);
    }

    // ==================== 查询方法 ====================

    @GetMapping("/task/{taskId}/predecessors")
    @Operation(summary = "查询任务的前置依赖", description = "查询指定任务的所有前置依赖")
    public Result<List<TaskDependencyVO>> getTaskPredecessors(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        String userId = UserContext.requireUserId();
        List<TaskDependencyVO> result = taskDependencyService.getTaskPredecessors(taskId, userId);
        return Result.success(result);
    }

    @GetMapping("/task/{taskId}/successors")
    @Operation(summary = "查询任务的后续依赖", description = "查询指定任务的所有后续依赖")
    public Result<List<TaskDependencyVO>> getTaskSuccessors(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        String userId = UserContext.requireUserId();
        List<TaskDependencyVO> result = taskDependencyService.getTaskSuccessors(taskId, userId);
        return Result.success(result);
    }

    @GetMapping("/task/{taskId}/path")
    @Operation(summary = "获取任务依赖路径", description = "获取指定任务的完整依赖路径")
    public Result<List<List<TaskDependencyVO>>> getTaskDependencyPath(
            @Parameter(description = "任务ID") @PathVariable String taskId) {
        String userId = UserContext.requireUserId();
        List<List<TaskDependencyVO>> result = taskDependencyService.getTaskDependencyPath(taskId, userId);
        return Result.success(result);
    }

    @GetMapping("/check-circular")
    @Operation(summary = "检查循环依赖", description = "检查两个任务之间是否会形成循环依赖")
    public Result<Boolean> checkCircularDependency(
            @Parameter(description = "前置任务ID") @RequestParam String predecessorId,
            @Parameter(description = "后续任务ID") @RequestParam String successorId) {
        Boolean hasCircular = taskDependencyService.checkCircularDependency(predecessorId, successorId);
        return Result.success(hasCircular);
    }

    @GetMapping("/validate")
    @Operation(summary = "验证依赖关系", description = "验证依赖关系是否有效")
    public Result<Object> validateDependency(
            @Parameter(description = "前置任务ID") @RequestParam String predecessorId,
            @Parameter(description = "后续任务ID") @RequestParam String successorId,
            @Parameter(description = "依赖类型") @RequestParam Integer dependencyType) {
        String userId = UserContext.requireUserId();
        
        // 检查循环依赖
        Boolean hasCircular = taskDependencyService.checkCircularDependency(predecessorId, successorId);
        
        // TODO: 添加其他验证逻辑
        
        return Result.success(Map.of(
            "hasCircular", hasCircular,
            "isValid", !hasCircular,
            "message", hasCircular ? "会形成循环依赖" : "依赖关系有效"
        ));
    }
}
